package com.zlkj.ssm.shop.web.controller;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.zlkj.ssm.shop.core.Services;
import com.zlkj.ssm.shop.core.cache.provider.SystemManager;
import com.zlkj.ssm.shop.core.page.PagerModel;
import com.zlkj.ssm.shop.web.tools.RequestHolder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 基类
 */
public abstract class BaseController<E extends PagerModel> {

	protected Logger logger = LoggerFactory.getLogger(getClass());
	protected String page_toList = null;
	protected String page_toEdit = null;
	protected String page_toAdd = null;

	public abstract Services<E> getService();

	@Autowired
	protected SystemManager systemManager;

	/**
	 * 分页加载数据
	 */
	@RequestMapping("loadData")
	@ResponseBody
	public PagerModel loadData(HttpServletRequest request, E e) {
		int offset = 0;
		int pageSize = 10;
		if (request.getParameter("start") != null) {
			offset = Integer.parseInt(request.getParameter("start"));
		}
		if (request.getParameter("length") != null) {
			pageSize = Integer.parseInt(request.getParameter("length"));
		}
		if (offset < 0)
			offset = 0;
		if (pageSize < 0) {
			pageSize = 10;
		}
		e.setOffset(offset);
		e.setPageSize(pageSize);
		PagerModel pager = getService().selectPageList(e);
		pager.setRecordsTotal(pager.getTotal());
		pager.setRecordsFiltered(pager.getTotal());
		return pager;
	}
	
	
	/**
	 * 返回到分页查询页面
	 */
	@RequestMapping("back")
	public String back(@ModelAttribute("e") E e, ModelMap model) throws Exception {
		return selectList(RequestHolder.getRequest(), e);
	}

	// start:*************************selectList*******************************************************************
	/**
	 * 公共的分页方法
	 */
	@RequestMapping("selectList")
	public String selectList(HttpServletRequest request, @ModelAttribute("e") E e) throws Exception {
		this.initPageSelect();// 由于prepare方法不具备一致性，加此代码解决init=y查询的时候条件不被清除干净的BUG
		setParamWhenInitQuery(e);

		int offset = 0;// 分页偏移量
		if (request.getParameter("pager.offset") != null) {
			offset = Integer.parseInt(request.getParameter("pager.offset"));
		}
		if (offset < 0)
			offset = 0;
		e.setOffset(offset);
		PagerModel pager = getService().selectPageList(e);
		if (pager == null) {
			pager = new PagerModel();
		}
		pager.setPagerSize((pager.getTotal() + pager.getPageSize() - 1) / pager.getPageSize());// 计算总页数

		selectListAfter(pager);
		request.setAttribute("pager", pager);
		request.setAttribute("pageNo", (offset / pager.getPageSize()) + 1);
		return page_toList;
	}

	protected void initPageSelect() {// 后台左边导航菜单的初始化查询方法
		logger.error("initPageSelect..init=n!");
	}

	protected void setParamWhenInitQuery(E e) {// 初始化查询的时候，会清除所有的查询参数(所以在e中的)，但可以设置不在e中的参数，然后在此方法中进行e.setXxx(参数)的方式进行保留。
		// BaseAction 的子类如有初始化页面的时候进行相关查询 ，则可以实现此方法。
	}

	protected void selectListAfter(PagerModel pager) {// 子类必须要实现的方法当分页查询后.解决了用户先点击新增按钮转到新增页面,然后点击返回按钮返回后,再点分页控件出错的BUG.原因是分页查询后未将pageUrl重新设置为正确的URL所致
		pager.setPagerUrl("selectList");
	}

	// end:*************************selectList*******************************************************************

	// start:*******************************页面跳转*********************************************************************
	/**
	 * 跳转到编辑页面
	 */
	@RequestMapping("toEdit")
	public String toEdit(@ModelAttribute("e") E e, ModelMap model) throws Exception {
		e = getService().selectOne(e);
		model.addAttribute("e", e);
		return page_toEdit;
	}

	/**
	 * 跳转到新增页面
	 */
	@RequestMapping("toAdd")
	public String toAdd(@ModelAttribute("e") E e, ModelMap model) throws Exception {
		e.clear();
		return page_toAdd;
	}

	// end:*******************************页面跳转*********************************************************************

	// satrat:****************************增删改********************************************************************
	/**
	 * 插入数据
	 */
	@RequestMapping(value = "insert", method = RequestMethod.POST)
	public String insert(HttpServletRequest request, @ModelAttribute("e") E e, RedirectAttributes flushAttrs) throws Exception {
		getService().insert(e);
		insertAfter(e);
		addMessage(flushAttrs, "操作成功！");
		return "redirect:selectList";
	}

	/**
	 * insert之后，selectList之前执行的动作，一般需要清除添加的E，否则查询会按照E的条件进行查询.
	 * 部分情况下需要保留某些字段，可以选择不清除
	 */
	protected void insertAfter(E e) {
	}

	/**
	 * 批量删除数据
	 */
	@RequestMapping(value = "deletes", method = RequestMethod.POST)
	public String deletes(HttpServletRequest request, String[] ids, @ModelAttribute("e") E e, RedirectAttributes flushAttrs) throws Exception {
		getService().deletes(ids);
		addMessage(flushAttrs, "操作成功！");
		return "redirect:selectList";
	}

	/**
	 * 更新数据
	 */
	@RequestMapping(value = "update", method = RequestMethod.POST)
	public String update(HttpServletRequest request, @ModelAttribute("e") E e, RedirectAttributes flushAttrs) throws Exception {
		getService().update(e);
		insertAfter(e);
		addMessage(flushAttrs, "操作成功！");
		return "redirect:selectList";
	}

	// end:****************************增删改********************************************************************



	protected void addMessage(ModelMap modelMap, String message) {
		modelMap.addAttribute("message", message);
	}

	protected void addWarning(ModelMap modelMap, String warning) {
		modelMap.addAttribute("warning", warning);
	}

	protected void addError(ModelMap modelMap, String warning) {
		modelMap.addAttribute("errorMsg", warning);
	}

	protected void addMessage(RedirectAttributes flushAttrs, String message) {
		flushAttrs.addFlashAttribute("message", message);
	}

	protected void addWarning(RedirectAttributes flushAttrs, String warning) {
		flushAttrs.addFlashAttribute("warning", warning);
	}

	protected void addError(RedirectAttributes flushAttrs, String warning) {
		flushAttrs.addFlashAttribute("errorMsg", warning);
	}

	protected String getUrl(HttpServletRequest request) throws Exception {
		return request.getScheme() + "://" + (80 == request.getServerPort() ? request.getServerName() : request.getServerName() + ":" + request.getServerPort());
	}

	protected String getDomain(HttpServletRequest request) throws Exception {
		return 80 == request.getServerPort() ? request.getServerName() : request.getServerName() + ":" + request.getServerPort();
	}

	protected HttpServletRequest getRequest() throws ServletException, IOException {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
	}

	protected HttpServletResponse getResponse() throws Exception {
		return ((ServletWebRequest) RequestContextHolder.getRequestAttributes()).getResponse();
	}

	protected HttpSession getSession() throws ServletException, IOException {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession(true);
	}

	protected HttpSession getSession(boolean create) throws ServletException, IOException {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession(create);
	}

}
